#define _CRT_SECURE_NO_WARNINGS 1

#include "Queue.h"

void Init(Queue* queue) {
	assert(queue);
	queue->size = 0;
	queue->front = NULL;
	queue->rear = NULL;
}


void Push(Queue* queue, valuetype val) {
	assert(queue);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL) {
		perror("Push(Queue*, valuetype) malloc failed.");
		return;
	}
	newnode->val = val; newnode->next = NULL;
	if (queue->size == 0) {
		queue->front = queue->rear = newnode;
	}
	else {
		queue->rear->next = newnode;
		queue->rear = newnode;
	}
	queue->size++;
}

void Pop(Queue* queue) {
	assert(queue && queue->size > 0);
	QueueNode* newfront = queue->front->next;
	free(queue->front);
	queue->front = newfront;
	queue->size--;
	
	if (queue->size == 0) {
		queue->rear = NULL;
	}
}


valuetype Front(Queue* queue) {
	assert(queue && queue->size > 0);
	return queue->front->val;
}

valuetype Rear(Queue* queue) {
	assert(queue && queue->size > 0);
	return queue->rear->val;
}


int Size(Queue* queue) {
	assert(queue);
	return queue->size;
}

bool Empty(Queue* queue) {
	assert(queue);
	return queue->size == 0;
}

void Destroy(Queue* queue) {
	assert(queue);
	QueueNode* node = queue->front;
	while (node) {
		QueueNode* next = node->next;
		free(node);
		node = next;
	}
	queue->size = 0;
	queue->front = queue->rear = NULL;
}